package com.imooc.springboot.dubbo.nilinili.consumer.filter;

import com.alibaba.nacos.common.util.HttpMethod;
import com.imooc.springboot.dubbo.nilinili.consumer.utils.JwtUtil;
import com.imooc.springboot.dubbo.nilinili.consumer.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    static final List<String> UserControllerAllowList =
            Arrays.asList("/user/login","/user/register","/user/getUserInfoByUserId");
    static final List<String> ErrorControllerAllowList =
            Arrays.asList("/error/exthrow");
    static final List<String> CategoryControllerAllowList =
            Arrays.asList("/category/selectSons","/category/selectCategoryId");
    static final List<String> AvatarControllerAllowList =
            Arrays.asList("/avatar/getAll");
    static final List<String> PhotoControllerAllowList =
            Arrays.asList(
                    "/photo/getHomePhotos",
                    "/photo/selectPhotos/",
                    "/photo/getAllPhotos",
                    "/photo/getPhotoById/",
                    "/photo/getShufflingUrls",
                    "/photo/getPhotosByUserId",
                    "/photo/getNewPhoto",
                    "/photo/addPhotoViewCount",
                    "/photo/getPhotoByName/");

    static final List<String> CommentControllerAllowList =
            Arrays.asList("/comment/selectCommentByPhotoId/");

    static final List<String> PhotographerControllerAllowList=
            Arrays.asList("/photographer/getAllUserInfo","/photographer/getUserWorks/");

    static final List<String> ALLOW_URL =
            ListIntegration(
                    UserControllerAllowList,
                    ErrorControllerAllowList,
                    CategoryControllerAllowList,
                    AvatarControllerAllowList,
                    PhotoControllerAllowList,
                    CommentControllerAllowList,
                    PhotographerControllerAllowList);

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT,PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*");

//        if (ALLOW_URL.contains(request.getRequestURI())){
//            filterChain.doFilter(request,response);
//            return;
//        }
        String requestURI = request.getRequestURI();
        for (String s : ALLOW_URL) {
            if (requestURI.startsWith(s)){
                filterChain.doFilter(request,response);
                return;
            }
        }

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            filterChain.doFilter(request,response);
            return;
        }

        String token = request.getHeader("token");

        if (token == null || token.equals("")){
            request.setAttribute("errorMessage","token不能为空");
            request.getRequestDispatcher("/error/exthrow").forward(request,response);
            return;
        }


        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            request.setAttribute("errorMessage","token异常");
            request.getRequestDispatcher("/error/exthrow").forward(request,response);
            return;
        }
        String userid = claims.getSubject();

        String redisKey = "login:"+userid;
        if (Objects.isNull(redisCache.getCacheObject(redisKey))){
            request.setAttribute("errorMessage","token非法");
            request.getRequestDispatcher("/error/exthrow").forward(request,response);
            return;
        }

        filterChain.doFilter(request,response);
    }

    // 合并放行路径
    public static List<String> ListIntegration(List<String> ...lists){
        return Arrays.stream(lists).flatMap(List::stream).collect(Collectors.toList());
    }


}
